package com.van.gateway.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.van.entity.ResPonObject;
import com.van.entity.constant.ResStatus;
import com.van.gateway.utils.GatewayServletUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetSocketAddress;
import java.util.Arrays;
import java.util.Date;

/**
 * 权限验证过滤器(网关鉴权)
 *
 * @author VanKa qq:2395073039
 * @date 2021/7/16 15:52
 */
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private static Logger logger = LoggerFactory.getLogger(AuthGlobalFilter.class);
//    @Autowired
//    private RedisService redisService;
    /**
     * 全局过滤路径
     */
    private String[] skipAuthUrls = {
            "/precloues/oauth/login/code",
            "/precloues/oauth/login/token"
    };

    private ObjectMapper objectMapper;

    public AuthGlobalFilter(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    /**
     * 过滤器
     *
     * @param exchange e
     * @param chain    c
     * @return e
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        Date d1 = new Date();
        ResPonObject o = new ResPonObject();
        o.setStatus(ResStatus.ERROR);

        String url = exchange.getRequest().getURI().getPath();
        InetSocketAddress remoteAddress = exchange.getRequest().getRemoteAddress();
        String ip = remoteAddress.getAddress().getHostAddress();

        log(0L,"游客登录",url,ip);
        //跳过不需要验证的路径
        if (null != skipAuthUrls && Arrays.asList(skipAuthUrls).contains(url)) {
            return chain.filter(exchange);
        }

        //获取token
        String token = exchange.getRequest().getHeaders().getFirst("token");
        o.setMsg("token 不存在！");
        //返回
        ServerHttpResponse resp = exchange.getResponse();
        return GatewayServletUtils.authError(resp, o);
    }



    /**
     * 打印日志
     */
    public void log(Long id,String name,String url,String ip){
        String r =/* DateUtils.sdf2.format(*/new Date()/*)*/ + "," + ip + "," + id + "," + name + "," + url +"\n";
        logger.info(r);
        //todo 日志待优化

    }
    /**
     * 过滤器执行顺序，数值越小，优先级越高
     *
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
